//
//  ChatFrame.swift
//  AirlineReservation
//
//  Created by Kevin on 2020/1/18.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

class ChatFrame: NSObject {

    var timeFrame:CGRect?
    var iconFrame:CGRect?
    var textFrame:CGRect?
    var rowHeigth:CGFloat?
    
    var chatBean:ChatBean? {
        didSet {
            createViewFrame()
        }
    }
    
    func createViewFrame() -> Void {
        // 时间
        let timeSize = chatBean?.time?.boundingRect(w: CGFloat(MAXFLOAT), h: CGFloat(MAXFLOAT), fontSize: 12)
        let timeX = 0
        let timeY = MARGIN10
        let timeW = SCREEN_WIDTH
        let timeH = timeSize!.height
        timeFrame = CGRect(x: CGFloat(timeX), y: timeY, width: timeW, height: timeH)
        // 头像
        let iconY = timeFrame!.maxY + MARGIN10
        let iconW = MARGIN50
        let iconH = iconW
        var iconX:CGFloat = 0
        if let type = chatBean?.type,type.elementsEqual("0") {
            iconX = SCREEN_WIDTH - iconW - MARGIN10
        }else {
            iconX = MARGIN10
        }
        iconFrame = CGRect(x: iconX, y: iconY, width: iconW, height: iconH)
        // 正文
        let textSize = chatBean?.text?.boundingRect(w: SCREEN_WIDTH * 0.6, h: CGFloat(MAXFLOAT), fontSize: 13)
        let textY = iconY
        let textW = textSize!.width + 40
        let textH = textSize!.height + 35
        var textX:CGFloat = 0
        if (chatBean?.type?.elementsEqual("0"))! {
            textX = SCREEN_WIDTH - 40 - textSize!.width - iconW - MARGIN10
        }else {
            textX = iconW + MARGIN10
        }
        textFrame = CGRect(x: textX, y: textY, width: textW, height: textH)
        if let img = chatBean?.picture {
            let imgW = SCREEN_WIDTH * 0.6
            textX = SCREEN_WIDTH - 30 - imgW - iconW - MARGIN10
            textFrame = CGRect(x: textX, y: textY, width: imgW + 40, height: img.size.height * 0.35)
        }
        // 行高
        rowHeigth = max(iconFrame!.maxY, textFrame!.maxY)
    }
 
    func getChatFrame() -> [ChatFrame]? {
        var temp = [ChatFrame]()
        guard let beans = getChatBean() else {
            return nil
        }
        for bean in beans {
            let chat = ChatFrame()
            chat.chatBean = bean
            temp.append(chat)
        }
        return temp
    }
    
    private func getChatBean() -> [ChatBean]? {
        var temp = [ChatBean]()
        guard let file = Bundle.main.path(forResource: "chat.plist", ofType: nil) else {
            return nil
        }
        guard let arrs = NSArray(contentsOfFile: file) else {
            return nil
        }
        for item in arrs {
            let bean = ChatBean(dict: item as! [String : String])
            if let hidden = temp.last?.time?.elementsEqual(bean.time ?? "") {
                bean.isHidden = hidden
            }
            temp.append(bean)
        }
        return temp
    }
}
